package dice.sinanya.db.attr;

import dice.sinanya.db.tools.DbUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;

import static dice.sinanya.system.MessagesAttr.customAttrList;

/**
 * @author SitaNya
 * 日期: 2019-08-03
 * 电子邮箱: sitanya@qq.com
 * 维护群(QQ): 162279609
 * 有任何问题欢迎咨询
 * 类说明:
 */
public class InputCustomAttr {
    private static final Logger log = LogManager.getLogger(InputCustomAttr.class.getName());


    public void insertAttr(String groupId, String attrName, String function) {
        insertAttr(Long.parseLong(groupId), attrName, function);
    }

    public void removeAttr(String groupId) {
        removeAttr(Long.parseLong(groupId));
    }

    /**
     * 将武器单体入库
     */
    public void insertAttr(Long groupId, String attrName, String function) {
        function = function.replace(".r", "").replace("r", "");
        //language=MySQL
        String sql = "REPLACE INTO test.customAttr(groupId, attrName, function) VALUES(?,?,?)";
        try (Connection conn = DbUtil.getConnection()) {
            try (PreparedStatement ps = conn.prepareStatement(sql)) {
                ps.setLong(1, groupId);
                ps.setString(2, attrName);
                ps.setString(3, function);
                if (ps.executeUpdate() <= 0) {
                    insertAttr(groupId, attrName, function);
                }
            }
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
        setInHash(groupId, attrName, function);
    }


    /**
     * 移除武器单体
     */
    public void removeAttr(Long groupId) {
        try (Connection conn = DbUtil.getConnection()) {
            //language=MySQL
            String sql = "delete from test.customAttr where groupId=?";
            try (PreparedStatement ps = conn.prepareStatement(sql)) {
                ps.setLong(1, groupId);
                if (ps.executeUpdate() <= 0) {
                    removeAttr(groupId);
                }
            }
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
        removeHash(groupId);
    }

    private void setInHash(Long groupId, String attrName, String function) {
        HashMap<String, String> attrList = customAttrList.getOrDefault(groupId, new HashMap<>());
        attrList.put(attrName, function);
        customAttrList.put(groupId, attrList);
    }

    private void removeHash(Long groupId) {
        customAttrList.remove(groupId);
    }
}
